package top.yongyan0624.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import top.yongyan0624.common.lang.CodeMsg;
import top.yongyan0624.common.lang.ResultVO;
import top.yongyan0624.entity.MyList;
import top.yongyan0624.entity.SysRole;
import top.yongyan0624.entity.SysUser;
import top.yongyan0624.entity.SysUserRole;
import top.yongyan0624.service.SysRoleService;
import top.yongyan0624.service.SysUserRoleService;
import top.yongyan0624.service.SysUserService;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 讽惘
 * @since 2021-05-13
 */
@RestController
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/users/register")
    public ResultVO register(@RequestParam String username, @RequestParam String password) {
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser != null) {
            return ResultVO.error(new CodeMsg("注册失败！用户已经存在！"));
        }
        SysUser user = new SysUser();
        user.setUsername(username);
        user.setPassword(bCryptPasswordEncoder.encode(password));
        sysUserService.save(user);

        //查询出新加入的user
        user = sysUserService.getByUsername(username);
        //进行角色的初始化
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user.getId());
        sysUserRole.setRoleId((long) 3); //注册的用户默认为普通用户,roleId:3
        boolean ok = sysUserRoleService.save(sysUserRole);

        if (ok) {
            return ResultVO.success("注册成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！出错了，注册失败！"));
    }

    @PostMapping("/users/Modification")
    public ResultVO Modification(@RequestBody SysUser sysUser) {
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        if (user != null) {
            sysUser.setPassword(user.getPassword());
            //根据id修改用户信息
            if (sysUserService.updateById(sysUser)) {
                return ResultVO.success("修改成功！");
            }
        }

        return ResultVO.error(new CodeMsg("修改出错啦！"));
    }

    @PostMapping("/users/ModificationPassword")
    public ResultVO ModificationPassword(@RequestBody SysUser sysUser) {
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        if (user != null) {
            user.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            //根据id修改用户信息
            if (sysUserService.updateById(user)) {
                return ResultVO.success("修改成功！");
            }
        }

        return ResultVO.error(new CodeMsg("修改出错啦！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/addUser")
    public ResultVO addUser(@RequestBody SysUser sysUser) {
        if (sysUser.getUsername() == null || sysUser.getPassword() == null) {
            return ResultVO.error(new CodeMsg("用户名或密码不能为空！"));
        }

        SysUser user = sysUserService.getByUsername(sysUser.getUsername());
        if (user != null) {
            return ResultVO.error(new CodeMsg("新增失败！用户已经存在！"));
        }

        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        sysUserService.save(sysUser);

        //查询出新加入的user
        user = sysUserService.getByUsername(sysUser.getUsername());
        //角色初始化
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user.getId());
        sysUserRole.setRoleId((long) 3);

        boolean ok = sysUserRoleService.save(sysUserRole);
        if (ok) {
            return ResultVO.success("新增成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！出错了，新增失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @RequestMapping("/admin/delUser/{id}")
    public ResultVO delUser(@PathVariable Long id) {
        boolean ok = sysUserService.removeById(id);

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", id));
        //清除权限缓存
        sysUserService.clearUserAuthorityInfo(id);
        if (ok) {
            return ResultVO.success("删除成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！不存在这个用户，删除失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @RequestMapping("/admin/delAllUser")
    public ResultVO delAllUser(@RequestBody MyList<Long> myList) {
        List<Long> ids = myList.getList();
        for (Long id : ids) {
            if (delUser(id).getCode() == 400) {
                return ResultVO.error(new CodeMsg("对不起！不存在这个用户:" + id + "，删除失败！"));
            }
        }
        return ResultVO.success("删除成功！");
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/updateUserModification")
    public ResultVO updateUserModification(@RequestBody SysUser sysUser) {

        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        if (user != null) {
            sysUser.setPassword(user.getPassword());

            boolean ok = sysUserService.updateById(sysUser);

            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()));

            if (sysUser.getRoles() != null && sysUser.getRoles().size() > 0) {
                List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>().in("name", sysUser.getRoles()));
                SysUserRole sysUserRole = new SysUserRole();
                for (SysRole role : roles) {
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRole.setRoleId(role.getId());

                    sysUserRoleService.save(sysUserRole);
                }
            }

            if (ok) {
                return ResultVO.success("修改成功！");
            }
        }


        return ResultVO.error(new CodeMsg("对不起！用户不存在，修改失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/updateUserModificationPassword")
    public ResultVO updateUserModificationPassword(@RequestBody SysUser sysUser) {

        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        if (user != null) {
            user.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));

            boolean ok = sysUserService.updateById(user);

            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", user.getId()));

            if (user.getRoles() != null && user.getRoles().size() > 0) {
                List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>().in("name", user.getRoles()));
                SysUserRole sysUserRole = new SysUserRole();
                for (SysRole role : roles) {
                    sysUserRole.setUserId(user.getId());
                    sysUserRole.setRoleId(role.getId());

                    sysUserRoleService.save(sysUserRole);
                }
            }

            if (ok) {
                return ResultVO.success("修改成功！");
            }
        }


        return ResultVO.error(new CodeMsg("对不起！用户不存在，修改失败！"));
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/queryUser")
    public ResultVO queryUser(@RequestParam Long pageNum, @RequestParam Long pageSize) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        Page<SysUser> pageData = sysUserService.page(page, new QueryWrapper<SysUser>().orderByDesc("last_login"));
        for (SysUser user : pageData.getRecords()) {
            //获取角色编码(ROLE_admin,ROLE_normal,)
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + user.getId())
                    .orderByAsc("priority"));

            if (roles.size() > 0) {
                for (SysRole role : roles) {
                    user.getRoles().add(role.getName());
                }
            }
        }

        return ResultVO.success(pageData);
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/queryUserByUsername")
    public ResultVO queryUserByUsername(@RequestParam String username, @RequestParam Long pageNum, @RequestParam Long pageSize) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        Page<SysUser> pageData = sysUserService.page(page, new QueryWrapper<SysUser>()
                .like(username != null && !username.equals(""), "username", username)
                .orderByAsc("username"));
        for (SysUser user : pageData.getRecords()) {
            //获取角色编码(ROLE_admin,ROLE_normal,)
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + user.getId())
                    .orderByAsc("priority"));

            if (roles.size() > 0) {
                for (SysRole role : roles) {
                    user.getRoles().add(role.getName());
                }
            }
        }

        return ResultVO.success(pageData);
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/queryUserByRoleName")
    public ResultVO queryUserByRoleName(@RequestParam String roleName, @RequestParam Long pageNum, @RequestParam Long pageSize) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        Page<SysUser> pageData = sysUserService.page(page,
                new QueryWrapper<SysUser>().inSql("id", "select sur.user_id " +
                        "from sys_user_role sur " +
                        "where sur.role_id in (select sr.id from sys_role sr where name = '" + roleName + "')")
                        .orderByAsc("username"));

        for (SysUser user : pageData.getRecords()) {
            //获取角色编码(ROLE_admin,ROLE_normal,)
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + user.getId())
                    .orderByAsc("priority"));

            if (roles.size() > 0) {
                for (SysRole role : roles) {
                    user.getRoles().add(role.getName());
                }
            }
        }

        return ResultVO.success(pageData);
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/countUser")
    public ResultVO countUser() {
        return ResultVO.success(sysUserService.count());
    }
}
